package com.wisdytech.linkdcs.equipLifeCycle.check.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.wisdytech.linkdcs.equipLifeCycle.check.model.CheckModelItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.PojoConvertUtil;
import com.wisdytech.linkdcs.equipLifeCycle.check.dao.ICheckDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.dao.ICheckDetailRecordDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.dao.ICheckModelItemDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.dao.ICheckRecordDao;
import com.wisdytech.linkdcs.equipLifeCycle.check.dto.CheckMonthSearchDto;
import com.wisdytech.linkdcs.equipLifeCycle.check.dto.CheckRecordSearchDto;
import com.wisdytech.linkdcs.equipLifeCycle.check.dto.ErrorEqDto;
import com.wisdytech.linkdcs.equipLifeCycle.check.dto.MonthCheckDayDto;
import com.wisdytech.linkdcs.equipLifeCycle.check.dto.MonthCheckDto;
import com.wisdytech.linkdcs.equipLifeCycle.check.model.Check;
import com.wisdytech.linkdcs.equipLifeCycle.check.model.CheckDetailRecord;
import com.wisdytech.linkdcs.equipLifeCycle.check.model.CheckRecord;
import com.wisdytech.linkdcs.equipLifeCycle.check.service.ICheckRecordService;
import com.wisdytech.linkdcs.equipLifeCycle.check.vo.CheckMonthVo;
import com.wisdytech.linkdcs.equipLifeCycle.check.vo.CheckRecordDetailVo;
import com.wisdytech.linkdcs.equipLifeCycle.check.vo.CheckRecordVo;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dailibo
 * @since 2018-06-05
 */
@Service
@Transactional
public class CheckRecordServiceImpl extends BaseService<ICheckRecordDao, CheckRecord> implements ICheckRecordService {

	
	private Logger logger =LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ICheckRecordDao iCheckRecordDao;
	
	@Autowired
	private ICheckDao iCheckDao;

    @Autowired
    private ICheckModelItemDao iCheckModelItemDao;
	
	@Autowired
	private ICheckDetailRecordDao iCheckDetailRecordDao;
	
	@Override
	public boolean addCheckRecord(List<CheckDetailRecord> records, String equipCode,String createUser) {
		

		Date date =new Date();
		String recordId=BaseUtil.getUUID();
		//整体检验是否成功
		boolean checkResult =true;
		
		//保存设备点检记录明细
		//补充记录信息
		for(CheckDetailRecord cr : records) {
			//有校验失败
			if(CommonConstants.CHECK_ERROR.equals(cr.getCheckResult())){
				checkResult=false;
			}
			
			cr.setPkId(BaseUtil.getUUID());
            CheckModelItem cim = iCheckModelItemDao.selectById(cr.getCheckItemId());
			cr.setCheckItemId(cim.getVersion());
			cr.setCheckRecordId(recordId);
			cr.setDelFlag(CommonConstants.DEL_FLAG);
			cr.setCreateUser(createUser);
			cr.setCreateDate(date);
			cr.setUpdateDate(date);
			cr.insert();
		}
		
		
		//保存设备点检记录
		CheckRecord record =new CheckRecord();
		record.setPkId(recordId);
		record.setCheckDate(date);
		record.setCheckUser(createUser);
		record.setEquipCode(equipCode);
		record.setDelFlag(CommonConstants.DEL_FLAG);
		record.setCreateUser(createUser);
		record.setCreateDate(date);
		record.setUpdateDate(date);
		
		Calendar calendar =Calendar.getInstance();
		calendar.setTime(date);
		record.setYear(String.valueOf(calendar.get(Calendar.YEAR)));
		record.setMonth(String.valueOf(calendar.get(Calendar.MONTH)+1));
		record.setDay(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
		
		//根据点检明细结果判断是否合格
		record.setCheckResult(
				checkResult?CommonConstants.CHECK_OK:CommonConstants.CHECK_ERROR);
		
		//修改点检列表最新点检时间
		Check check =new Check();
		check.setLastDate(date);
		check.setUpdateUser(createUser);
		check.setUpdateDate(date);
		EntityWrapper<Check> ew=new EntityWrapper<>();
		check.update(ew.eq("EQUIP_CODE", equipCode));
		
		return record.insert();
	}

	@Override
	public PageInfo<CheckRecordVo> listCheckRecord(Filter filter, CheckRecordSearchDto sDto) {
		
		List<CheckRecordVo>  result =
				this.beforeList(ICheckRecordDao.class, filter).selectCheckRecordDetail(sDto);
		
		
		return new PageInfo<>(result);
	}

	@Override
	public List<ErrorEqDto> listTop10ErrorEq(String year, String month) {
		Filter filter =new Filter();
		filter.setNum(1);
		filter.setSize(10);
		List<ErrorEqDto>  result =
				this.beforeList(ICheckRecordDao.class, filter).selectErrorEq(year, month);
	
		return result;
	}

	@Override
	public PageInfo<CheckMonthVo> getMonthCheckRecord(Filter filter, CheckMonthSearchDto dto, String year,
			String month) {
		//分页查询设备点检项目列表
		List<MonthCheckDto> result =
				this.beforeList(ICheckModelItemDao.class, filter).selectItems(dto);
		
		PageInfo<MonthCheckDto> pageInfoChecks=new PageInfo<>(result);
		
		
		//根据点检项目查询月度点检记录
		List<CheckMonthVo>  checkMonths=
				PojoConvertUtil.convertPojos(pageInfoChecks.getList(), CheckMonthVo.class);
		
		//补充月度信息
		for(CheckMonthVo vo :checkMonths) {
			//查询月度下指定设备的月度点检记录
			List<MonthCheckDayDto>  dayDtosErrors=
					iCheckRecordDao.selectDayDetail(vo.getPkId(), "1", vo.getEqCode(),year,month);
			
			List<MonthCheckDayDto>  dayDtosOKs=
					iCheckRecordDao.selectDayDetail(vo.getPkId(), "0", vo.getEqCode(),year,month);
			
			
			
			
			setMonthValueDetail(vo, dayDtosErrors,dayDtosOKs);
		}
		PageInfo<CheckMonthVo> checkVoInfos =new PageInfo<>(checkMonths);
		checkVoInfos.setPageNum(pageInfoChecks.getPageNum());
		checkVoInfos.setPageSize(pageInfoChecks.getPageSize());
		checkVoInfos.setTotal(pageInfoChecks.getTotal());
		return checkVoInfos;
	}

	@Override
	public List<CheckRecordDetailVo> getMonthCheckDetail(String eqCode, String checkItemCode, String year,String month,String day) {
		
		return iCheckDetailRecordDao.selectMonthDetail(eqCode, checkItemCode, year, month, day);
		
	}
	
	/**
	 * 调用
	 * @param vo
	 * @param dayDtos
	 */
	private void setMonthValueDetail(CheckMonthVo vo,
			List<MonthCheckDayDto>  dayDtosErrors,
			List<MonthCheckDayDto>  dayDtosOks) {
		//错误的信息
		for(MonthCheckDayDto dto : dayDtosErrors) {
			String setter ="setValue"+dto.getDay();
			try {
				Method method =
						vo.getClass().getMethod(setter, String.class);
				
				method.invoke(vo, "-1");
				
			} catch (NoSuchMethodException | SecurityException |
					IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		//正确的信息
		for(MonthCheckDayDto dto : dayDtosOks) {
			String setter ="setValue"+dto.getDay();
			String getter ="getValue"+dto.getDay();
			try {
				
				Method getMethod =
						vo.getClass().getMethod(getter);
				
				Object value =getMethod.invoke(vo);
				//如果有错误信息，则不处理
				if(null != value) {
					continue;
				}
				
				Method method =
						vo.getClass().getMethod(setter, String.class);
				
				method.invoke(vo, "1");
				
			} catch (NoSuchMethodException | SecurityException |
					IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
	}

}
